import { FFmpegTask } from './base'

/**
 * 视频压缩选项
 */
export interface CompressOptions {
  input: string
  output: string
  quality?: 'low' | 'medium' | 'high' | 'custom' // 质量预设
  targetSize?: number // 目标文件大小(MB)
  videoBitrate?: string // 自定义视频码率
  audioBitrate?: string // 自定义音频码率
  resolution?: string // 输出分辨率
  crf?: number // CRF值(0-51, 越小质量越好) 推荐18-28
  preset?: 'ultrafast' | 'superfast' | 'veryfast' | 'faster' | 'fast' | 'medium' | 'slow' | 'slower' | 'veryslow'
}

/**
 * 视频压缩
 */
export function compressVideo(options: CompressOptions): FFmpegTask {
  const args: string[] = ['-i', options.input, '-y']

  // H.264 编码
  args.push('-c:v', 'libx264')
  args.push('-c:a', 'aac')

  // 根据质量预设设置参数
  if (options.quality && options.quality !== 'custom') {
    const qualityPresets = {
      low: { crf: 28, preset: 'fast' as const, audioBitrate: '96k' },
      medium: { crf: 23, preset: 'medium' as const, audioBitrate: '128k' },
      high: { crf: 18, preset: 'slow' as const, audioBitrate: '192k' }
    }

    const preset = qualityPresets[options.quality]
    args.push('-crf', String(preset.crf))
    args.push('-preset', preset.preset)
    args.push('-b:a', preset.audioBitrate)
  } else {
    // 自定义参数
    if (options.crf !== undefined) {
      args.push('-crf', String(options.crf))
    } else {
      args.push('-crf', '23') // 默认值
    }

    if (options.preset) {
      args.push('-preset', options.preset)
    }

    if (options.videoBitrate) {
      args.push('-b:v', options.videoBitrate)
    }

    if (options.audioBitrate) {
      args.push('-b:a', options.audioBitrate)
    }
  }

  // 分辨率
  if (options.resolution) {
    args.push('-s', options.resolution)
  }

  // 优化选项
  args.push('-movflags', '+faststart') // 优化网络播放
  args.push('-pix_fmt', 'yuv420p') // 兼容性

  args.push(options.output)

  return new FFmpegTask(args, options.input)
}

/**
 * 按目标大小压缩（两遍编码）
 */
export function compressToTargetSize(
  input: string,
  output: string,
  targetSizeMB: number,
  duration: number
): FFmpegTask {
  // 计算目标码率
  const targetBitrate = Math.floor((targetSizeMB * 8192) / duration) // kbps
  const videoBitrate = Math.floor(targetBitrate * 0.9) // 视频占90%
  const audioBitrate = Math.min(128, Math.floor(targetBitrate * 0.1)) // 音频占10%

  const args: string[] = [
    '-i',
    input,
    '-y',
    '-c:v',
    'libx264',
    '-b:v',
    `${videoBitrate}k`,
    '-c:a',
    'aac',
    '-b:a',
    `${audioBitrate}k`,
    '-preset',
    'medium',
    '-movflags',
    '+faststart',
    output
  ]

  return new FFmpegTask(args, input)
}
